package com.house.controller;

import com.house.entity.Area;
import com.house.entity.UserInf;
import com.house.service.AdminService;
import com.house.service.AreaService;
import com.house.service.HouseService;
import com.house.service.UserService;
import com.house.vo.AreaCountVo;
import com.house.vo.JsonVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class CommonController {

    @Autowired
    private UserService userService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private HouseService houseService;

    @GetMapping("/welcome")
    public  ModelAndView welcome(){
        ModelAndView modelAndView = new ModelAndView("welcome");
        return modelAndView;
    }

    @GetMapping("/index")
    public  ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("index");
        return modelAndView;
    }
    @GetMapping("/api/getcount")
    @ResponseBody
    public JsonVo getcount(){
        List<AreaCountVo> areaCountVoList= new ArrayList<>();
        List<Area> areas = areaService.findall();
        for(Area area:areas){
            int count = houseService.countbyArea(area.getArea());
            areaCountVoList.add(new AreaCountVo(area.getArea(),count));
        }
        JsonVo jsonVo = new JsonVo();
        jsonVo.setData(areaCountVoList);
        jsonVo.setCode(200);
        return jsonVo;

    }
    @RequestMapping("/head")
    public ModelAndView head(HttpSession session){
        UserInf userInf= (UserInf) session.getAttribute("userInf");
//        //System.out.println(userInf.getName());
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("userInf",userInf);
        modelAndView.setViewName("common/head");
        return modelAndView;
    }

    @RequestMapping(value = "/user/uploadimg")
    @ResponseBody
    public void uploadImg(@RequestParam(value = "files",required = false) MultipartFile multipartFile, HttpServletRequest request,HttpSession session) throws Exception {
        String realpath = "";
        //获取文件名
        String name = "";
        if (multipartFile != null) {
            long size = multipartFile.getSize();

            name = multipartFile.getOriginalFilename();//直接返回文件的名字
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());//我这里取得文件后缀
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//文件保存进来，我给他重新命名，数据库保存有原本的名字，所以输出的时候再把他附上原本的名字就行了。
            String filepath = "D:\\uploadFiles";//获取项目路径到webapp
//            String filepath = "D:\\uploadFiles";//获取项目路径到webapp
            File file = new File(filepath);
            if (!file.exists()) {//目录不存在就创建
                file.mkdirs();
            }

            multipartFile.transferTo(new File(file + "/" + fileName + "." + subffix));//保存文件
            realpath = file + "/" + fileName + "." + subffix;
        
            String url="/api/file/"+ fileName + "." + subffix;

            if (session.getAttribute("userInf")!=null){
                UserInf userInf= (UserInf) session.getAttribute("userInf");
                userService.updateProfillById(url,userInf.getId());
            }

        }
    }
    @RequestMapping(value = "/api/house/upload")
    @ResponseBody
    public JsonVo houseUpload(@RequestParam(value = "files",required = false) MultipartFile multipartFile, HttpServletRequest request,HttpSession session) throws Exception {
        JsonVo jsonVo= new JsonVo();
        String realpath = "";
        //获取文件名
        String name = "";
        if (multipartFile != null) {
            long size = multipartFile.getSize();

            name = multipartFile.getOriginalFilename();//直接返回文件的名字
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());//我这里取得文件后缀
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//文件保存进来，我给他重新命名，数据库保存有原本的名字，所以输出的时候再把他附上原本的名字就行了。
            String filepath = "D:\\uploadFiles";//获取项目路径到webapp
            File file = new File(filepath);
            if (!file.exists()) {//目录不存在就创建
                file.mkdirs();
            }

            multipartFile.transferTo(new File(file + "/" + fileName + "." + subffix));//保存文件
            realpath = file + "/" + fileName + "." + subffix;
            String url="/api/file/"+ fileName + "." + subffix;

            if (session.getAttribute("userInf")==null){ //用户未登录，返回空值
                jsonVo.setCode(500);
                jsonVo.setData("请先登录！");
                return jsonVo;
            }
            List<String > urlList;
            if (session
            .getAttribute("imageUrlList")==null){ //图片列表为空，此时用户上传第一张图片，在session中创建图片列表
                urlList=new ArrayList<>();
                urlList.add(url);
                session.setAttribute("imageUrlList",urlList);
            }else { //session中已有其他图片，保存即可
                urlList= (List<String>) session.getAttribute("imageUrlList");
                urlList.add(url);
                session.setAttribute("imageUrlList",urlList);
            }
            jsonVo.setCode(200);
            jsonVo.setData(url);
        }
        else {
            jsonVo.setCode(500);
        }
        return jsonVo;
    }
}
